<script setup>
    import {ref} from 'vue'
    import useUserInfoStore from '@/stores/userInfo.js'
    import {useTokenStore} from '@/stores/token.js'
    import { ElMessage, ElMessageBox } from 'element-plus';
    import {useRouter} from 'vue-router'
    import {adminPageQueryService, adminInfoUpdateService, adminDeleteService, adminInfoGetService, adminRegisterService} from '@/api/admin.js'
import { adminPasswordResetService } from '../../../api/admin';

    const uploadRef = ref()
    const userInfoStore = useUserInfoStore();
    const tokenStore = useTokenStore();
    const router = useRouter();

    //列表的物品总数
    const itemsTotal = ref(1);

    console.log(userInfoStore.info.name)
    const isRoot = ref(userInfoStore.info.name == 'root')
    
    //定义表单校验规则
    const rules = {
        name: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 2, max: 16, message: '长度为2~16位非空字符', trigger: 'blur' }
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 5, max: 16, message: '密码长度为5~16位，只能为大小写英文字母与数字符号', trigger: 'blur' }
        ],
        phone: [
            { required: true, message: '电话号码不能为空', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '电话号码格式不正确', trigger: 'blur' }
        ],
        email: [
            { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式不正确', trigger: 'blur' }
        ],
        identifyNumber: [
            { required: true, message: '请输入身份证号', trigger: 'blur' },
        ],
    }

    //系统管理人员分页查询的表单结构
    const adminPageQueryData = ref({
        page: 1,
        pageSize: 5,
        id: null,
        name: null,
        phone: null,
        sex: null,
        email: null,
        identifyNumber: null
    })

    const admins = ref([])

    //分页查询获取用户列表
    const getAdmins = async()=>{
        let result = await adminPageQueryService(adminPageQueryData.value);
        admins.value = result.records
        itemsTotal.value = result.total
    }
    //页面加载时获取一次所有用户
    getAdmins()
    
    //分页大小改变时重新分页查询
    const handleSizeChange = (val) => {
        adminPageQueryData.value.pageSize = val
        getAdmins()
    }
    //分页页码改变时重新分页查询
    const handleCurrentChange = (val) => {
        adminPageQueryData.value.page = val
        getAdmins()
    }

    //是否在编辑用户，若为true则呼出右侧编辑窗口
    const isEditing = ref(false)
    //当前用户，用于承载编辑用户与添加用户的表单
    const currentUser = ref({})

    const updateUserInfo = async ()=>{
        console.log('Updating user data:', currentUser.value); // 打印更新的用户数据
        let result = await adminInfoUpdateService(currentUser.value);
        ElMessage.success(result.data ? result.data : '修改成功');
    }

    //图片上传成功的回调函数
    const uploadSuccess = (result)=>{
        console.log(result)
        if(result.code === 1){
            currentUser.value.image = result.data;
        }
    }

    //提交编辑
    const resetPassword = async () =>{
        //调用接口
        let result = await adminPasswordResetService(currentUser.value.id);
        ElMessage.success(result.data? result.data : '修改成功');
    }

    //编辑用户
    const editUser = async (row) =>{
        isEditing.value = true   
        let result = await adminInfoGetService(row.id)
        console.log('Fetched user data:', result.data); // 打印获取到的用户数据
        currentUser.value = result.data;
    }

    //删除用户使用ElMessageBox判断
    const deleteUser = (row) =>{
        ElMessageBox.confirm(
            '要删除该用户吗?',
            'Warning',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then( async () => {
                let id = row.id;
                let result = await adminDeleteService(id)
                ElMessage.success(result.msg? result.msg : '删除成功');
                getAdmins()
        }).catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })

    }

    //取消编辑
    const cancelClickEditing = () =>{
        isEditing.value = false
    }

    //提交编辑
    const confirmClickEditing = async () =>{
        await updateUserInfo()
        isEditing.value = false
        await getAdmins()
    }

    //是否在添加新用户，若为true则呼出右侧新增用户窗口
    const isAdding = ref(false)

    const addAdmin = async() => {
         //调用接口
        currentUser.value.repeatPassword = currentUser.value.password
        let result = await adminRegisterService(currentUser.value);
        ElMessage.success(result.msg? result.msg : '新增成功');
    }

    
    //添加新用户，初始化currentUser表单
    const addAdminButton = () =>{
        currentUser.value = {
            id: null,
            name: '',
            password: '',
            repeatPassword: '',
            image: '',
            phone: '',
            email: '',
            sex: '',
            identifyNumber: '',
        }
        isAdding.value = true;
    }

    //取消新增用户
    const cancelClickAdding = () =>{
        isAdding.value = false
    }

    //提交新增用户
    const confirmClickAdding = async () =>{
        await addAdmin()
        isAdding.value = false
        await getAdmins()
    }


</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>系统人员管理</span>
            </div>
        </template>

        <div>
            <!-- 顶部栏，包含分页查询过滤条件，以及创建新用户 -->
            <el-form class="search-filter" :model="adminPageQueryData">
                <el-form-item label="用户名">
                    <el-input v-model="adminPageQueryData.name" type="text"></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="adminPageQueryData.phone" type="text"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="adminPageQueryData.email" type="text"></el-input>
                </el-form-item>
                <el-form-item>
                        <el-button type="primary" @click="getAdmins">搜索</el-button>
                </el-form-item>
                <el-form-item>
                        <el-button @click="addAdminButton" :disabled="!isRoot">新增系统人员</el-button>
                </el-form-item>
            </el-form>
        </div>

        <hr style="background-color: #eee; height: 1px; border: none;"/>

        <!-- 用户表格 -->
        <el-table :data="admins" style="width: 100%">
            <el-table-column prop="id" label="ID" width="180" sortable  />
            <el-table-column prop="name" label="用户名" width="180" sortable  />
            <el-table-column prop="phone" label="电话" sortable />
            <el-table-column prop="email" label="邮箱" sortable />
            <el-table-column prop="jugSum" label="审核单量" sortable />
            <el-table-column prop="operations" label="操作" fixed="right">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="editUser(scope.row)" :disabled="!isRoot">编辑</el-button>
                    <el-button link type="danger" size="small" @click="deleteUser(scope.row)" :disabled="!isRoot">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <!-- 页码切换组件 -->
        <div class="pagination-block">
            <el-pagination layout="prev, pager, next, sizes" :total="itemsTotal" :page-size="adminPageQueryData.pageSize"
            v-model:current-page="adminPageQueryData.page"
            v-model:page-size="adminPageQueryData.pageSize"
            
            :page-sizes="[5, 10, 20, 50]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
    </el-card>

    <!-- 编辑用户的侧边界面 -->
    <el-drawer v-model="isEditing" :direction="rtl" size="50%">
        <template #header>
            <h4>编辑 {{ currentUser.name }} 信息</h4>
        </template>
        <template #default>
            <div class="form-edit-user" >

                <div class="form-edit-user-avatar">
                    <el-avatar :src="currentUser.image" :size="100"  @click="uploadRef.$el.querySelector('input').click()" />
                    <el-row>
                        <el-col :span="12">
                            <el-upload 
                                ref="uploadRef"
                                class="avatar-uploader" 
                                :show-file-list="false"
                                :auto-upload="true"
                                action="/api/upload"
                                accept="image/png, image/jpeg"
                                name="file"
                                :headers="{'Token':tokenStore.token}"
                                :on-success="uploadSuccess"
                                >
                            </el-upload>
                        </el-col>
                    </el-row>
                </div>

                <el-row>
                    <el-col :span="18">
                        <el-form :model="currentUser" :rules="rules" label-width="150px" size="large">
                            <el-form-item label="ID">
                                <el-input v-model="currentUser.id" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="用户名" prop="name">
                                <el-input v-model="currentUser.name"></el-input>
                            </el-form-item>
                            <el-form-item label="重置密码" prop="passwordReset">
                                <el-button @click="resetPassword">重置密码</el-button>
                            </el-form-item>
                            <el-form-item label="电话号码" prop="phone">
                                <el-input v-model="currentUser.phone"></el-input>
                            </el-form-item>
                            <el-form-item label="邮箱" prop="email">
                                <el-input v-model="currentUser.email"></el-input>
                            </el-form-item>
                            <el-form-item label="性别" prop="sex">
                                <el-radio-group v-model="currentUser.sex">
                                    <el-radio label="男" value="'男'"></el-radio>
                                    <el-radio label="女" value="'女'"></el-radio>
                                    <el-radio label="其他" :value="'其他'"></el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="身份证号" prop="identifyNumber">
                                <el-input v-model="currentUser.identifyNumber"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
        <div style="flex: auto">
            <el-button @click="cancelClickEditing">取消</el-button>
            <el-button type="primary" @click="confirmClickEditing">确认</el-button>
        </div>
        </template>
  </el-drawer>


  <!-- 新增用户的侧边界面 -->
  <el-drawer v-model="isAdding" :direction="rtl" size="50%">
        <template #header>
            <h4>新增系统人员</h4>
        </template>
        <template #default>
            <div class="form-edit-user" >

                <div class="form-edit-user-avatar">
                    <el-avatar :src="currentUser.image" :size="100"  @click="uploadRef.$el.querySelector('input').click()" />
                    <el-row>
                        <el-col :span="12">
                            <el-upload 
                                ref="uploadRef"
                                class="avatar-uploader" 
                                :show-file-list="false"
                                :auto-upload="true"
                                action="/api/upload"
                                accept="image/png, image/jpeg"
                                name="file"
                                :headers="{'Token':tokenStore.token}"
                                :on-success="uploadSuccess"
                                >
                            </el-upload>
                        </el-col>
                    </el-row>
                </div>

                <el-row>
                    <el-col :span="18">
                        <el-form :model="currentUser" :rules="rules" label-width="150px" size="large">
                            <el-form-item label="用户名" prop="name">
                                <el-input v-model="currentUser.name"></el-input>
                            </el-form-item>
                            <el-form-item label="密码" prop="password">
                                <el-input v-model="currentUser.password"></el-input>
                            </el-form-item>
                            <el-form-item label="电话号码" prop="phone">
                                <el-input v-model="currentUser.phone"></el-input>
                            </el-form-item>
                            <el-form-item label="邮箱" prop="email">
                                <el-input v-model="currentUser.email"></el-input>
                            </el-form-item>
                            <el-form-item label="性别" prop="sex">
                                <el-radio-group v-model="currentUser.sex">
                                    <el-radio label="男" value="'男'"></el-radio>
                                    <el-radio label="女" value="'女'"></el-radio>
                                    <el-radio label="其他" :value="'其他'"></el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="身份证号" prop="identifyNumber">
                                <el-input v-model="currentUser.identifyNumber"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
        <div style="flex: auto">
            <el-button @click="cancelClickAdding">取消</el-button>
            <el-button type="primary" @click="confirmClickAdding">确认</el-button>
        </div>
        </template>
  </el-drawer>

</template>

<style scoped>
    .search-filter {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }

    .pagination-block{
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .form-edit-user {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .form-edit-user-avatar {
        display: flex;
        justify-content: center;
        padding: 32px;
    }
    
</style>